/**
 * @Title: SMSBaseTools.java
 * @Package com.ninelephas.whale.common.tools
 * @Description:系统短信发送底层工具
 * @author Shawn
 * @date 2016年10月10日 上午10:56:09
 * @version V1.0
 */
package com.warrior.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;

import com.warrior.configer.ConfigHelper;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;


/**
 * @author Shawn
 * @ClassName: SMSBaseTools
 * @Description: 系统短信发送底层工具
 */
public final class SMSMessageBaseTools {
    /**
     * Logger for this class
     */
    private static final Logger logger = LogManager.getLogger(SMSMessageBaseTools.class);

    private static final String ENCODING = "UTF-8";

    private String url;
    private String id;
    private String pwd;
    private String account;


    /**
     * <p>
     * Title:
     * </p>
     * <p>
     * Description: 用作初始化短信发送工具,在调用先需先初始化 SMSBaseTools
     * </p>
     *
     * @param url
     * @param id
     * @param pwd
     * @param account
     */
    public SMSMessageBaseTools(String url, String id, String account, String pwd) {
        this.url = url;
        this.id = id;
        this.pwd = pwd;
        this.account = account;
    }

    /**
     * @param @param  content
     * @param @param  mobile
     * @param @return
     * @param @throws SMSMessageException    设定文件
     * @return String    返回类型
     * @throws
     * @Title: messageSendTools
     * @Description: 独立短信模块
     * @author 杨智刚
     */
    public String messageSendTools(String content, String mobile) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("messageSendTools(String content={}, String mobile={}) - start", content, mobile); //$NON-NLS-1$
        }

        // 打开httpclient连接
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod();
        URI base;
        try {
            base = new URI(url, false);
            method.setURI(new URI(base, "", false));
            String ids = id;
            String pswd = pwd;
            String sendAccount = account;
            String extno = null;
            String action = "send";
            String sendTime = null;
            String contentCleaned = ConfigHelper.getConfig().getString("SMS.SIGN")+Jsoup.clean(content, Whitelist.none()).replace("&nbsp;", "").trim();// 过滤所有html代码
            method.getParams().setContentCharset(ENCODING);
            // 填入各个表单域的值
            NameValuePair[] data = new NameValuePair[]{
                    new NameValuePair("userid", ids),
                    new NameValuePair("account", sendAccount),
                    new NameValuePair("password", pswd),
                    new NameValuePair("mobile", mobile),
                    new NameValuePair("content", contentCleaned),
                    new NameValuePair("sendTime", sendTime),
                    new NameValuePair("action", action),
                    new NameValuePair("extno", extno),
            };

            method.setRequestBody(data);
            // 执行发送
            int result;
            result = client.executeMethod(method);
            // 200表示成功--> HttpStatus.SC_OK,这里的异常主要是通信异常
            if (result == HttpStatus.SC_OK) {
                InputStream in;
                in = method.getResponseBodyAsStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    // 从指定的1024字节数组开始，从offset off到该字节数组输出流写入len字节。
                    baos.write(buffer, 0, len);
                }

                // 将字节流以utf-8形式编码
                String returnString;

                returnString = URLDecoder.decode(baos.toString(), ENCODING);
                if (logger.isDebugEnabled()) {
                    logger.debug("messageSendTools(String, String) - end"); //$NON-NLS-1$
                }

                return returnString;
            } else {
                throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
            }
        } catch (NullPointerException | IOException e) {
            logger.error(e, e.fillInStackTrace());
            throw new Exception(e.getMessage());
        }

    }


}
